const util = require("util");
const multer = require("multer");
const { GridFsStorage } = require("multer-gridfs-storage");
const dbConfig = require("../config/db");

const storage = new GridFsStorage({
  url: dbConfig.url + dbConfig.database,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  file: async (req, file) => {
    const match = ["image/png", "image/jpeg", "image/gif"];

    // file.stream为文件流，可以获取图片的宽高
    const stream = file.stream;
    const filename = `${Date.now()}-bezkoder-${file.originalname}`;
    if (match.indexOf(file.mimetype) === -1) {
      return filename;
    }

    // console.log('metadata', metadata)
    // 将图片宽高信息保存到 metadata 中
    return {
      bucketName: dbConfig.imgBucket,
      filename,
    };
  },
});

const uploadFiles = multer({ storage: storage }).array("file", 10);
// const uploadFiles = multer({ storage: storage }).single("file");
const uploadFilesMiddleware = util.promisify(uploadFiles);
module.exports = uploadFilesMiddleware;
